"""
全局快捷键管理器
"""
import keyboard
from PyQt6.QtCore import QObject, pyqtSignal, QTimer
import threading
import time


class HotkeyManager(QObject):
    """快捷键管理器"""
    
    # 信号
    hotkey_pressed = pyqtSignal()
    hotkey_released = pyqtSignal()
    
    def __init__(self):
        super().__init__()
        self.current_hotkey = None
        self.is_registered = False
        self._lock = threading.Lock()
        self.is_pressed = False
        self.last_press_time = 0
        self.min_press_duration = 0.1  # 最短按压时间（秒）
        
        # 使用多种检测方式
        self.release_timer = QTimer()
        self.release_timer.timeout.connect(self._check_release)
        self.release_timer.setInterval(50)  # 减少到50ms，更快响应
        
        # 记录需要监听的按键
        self.monitored_keys = []
        self.release_callbacks = []
    
    def register_hotkey(self, hotkey: str):
        """注册快捷键"""
        # 先注销旧的快捷键
        self.unregister_hotkey()
        
        try:
            with self._lock:
                self.current_hotkey = hotkey
                
                # 解析快捷键，获取所有按键
                self.monitored_keys = [k.strip().lower() for k in hotkey.split('+')]
                print(f"[HotkeyManager] 监听的按键: {self.monitored_keys}")
                
                # 注册按下事件（使用keyboard的add_hotkey）
                keyboard.add_hotkey(
                    hotkey,
                    self._on_hotkey_pressed,
                    suppress=False
                )
                
                # 为每个按键注册释放监听
                self._register_release_listeners()
                
                self.is_registered = True
                print(f"[HotkeyManager] 快捷键已注册: {hotkey}")
                return True
        except Exception as e:
            print(f"[HotkeyManager] 注册快捷键失败: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    def _register_release_listeners(self):
        """为所有按键注册释放监听"""
        # 清理旧的监听
        for callback in self.release_callbacks:
            try:
                keyboard.unhook(callback)
            except:
                pass
        self.release_callbacks.clear()
        
        # 为每个按键添加释放监听
        for key in self.monitored_keys:
            try:
                # 使用on_release_key监听具体按键的释放
                callback = keyboard.on_release_key(key, self._on_key_released)
                self.release_callbacks.append(callback)
                print(f"[HotkeyManager] 已为 '{key}' 注册释放监听")
            except Exception as e:
                print(f"[HotkeyManager] 为 '{key}' 注册释放监听失败: {e}")
    
    def _on_key_released(self, event):
        """单个按键释放回调"""
        if not self.is_pressed:
            return
        
        # 检查是否所有按键都已释放
        # 延迟10ms后检查，确保所有按键状态都更新了
        QTimer.singleShot(10, self._delayed_check_release)
    
    def unregister_hotkey(self):
        """注销快捷键"""
        if not self.is_registered or not self.current_hotkey:
            return
        
        try:
            with self._lock:
                # 停止定时器
                self.release_timer.stop()
                
                # 移除快捷键
                keyboard.remove_hotkey(self.current_hotkey)
                
                # 移除释放监听
                for callback in self.release_callbacks:
                    try:
                        keyboard.unhook(callback)
                    except:
                        pass
                self.release_callbacks.clear()
                
                self.is_registered = False
                self.is_pressed = False
                print(f"[HotkeyManager] 快捷键已注销: {self.current_hotkey}")
        except Exception as e:
            print(f"[HotkeyManager] 注销快捷键失败: {e}")
    
    def _on_hotkey_pressed(self):
        """快捷键按下回调"""
        print("[HotkeyManager] ========== 快捷键按下 ==========")
        if not self.is_pressed:
            self.is_pressed = True
            self.last_press_time = time.time()
            print("[HotkeyManager] 发送 hotkey_pressed 信号")
            self.hotkey_pressed.emit()
            # 同时启动定时器作为备用检测
            self.release_timer.start()
            print("[HotkeyManager] 启动备用定时器检测（50ms间隔）")
        else:
            print("[HotkeyManager] 已经在按下状态，忽略")
    
    def _delayed_check_release(self):
        """延迟检查释放（由按键释放事件触发）"""
        if not self.is_pressed:
            return
        
        print("[HotkeyManager] === 检测到按键释放事件，开始检查 ===")
        self._check_all_keys_released()
    
    def _check_release(self):
        """定时器备用检测（轮询方式）"""
        if not self.is_pressed:
            return
        
        self._check_all_keys_released()
    
    def _check_all_keys_released(self):
        """检查所有按键是否都已释放"""
        try:
            # 映射键名
            key_map = {
                'ctrl': 'ctrl',
                'alt': 'alt', 
                'shift': 'shift',
                'win': 'windows'
            }
            
            # 检查所有键是否都已释放
            all_released = True
            pressed_keys = []
            
            for key in self.monitored_keys:
                mapped_key = key_map.get(key, key)
                try:
                    if keyboard.is_pressed(mapped_key):
                        all_released = False
                        pressed_keys.append(mapped_key)
                except:
                    # 某些键可能检测失败，忽略
                    pass
            
            if pressed_keys:
                # 仍有按键按下，每秒输出一次
                current_time = time.time()
                if not hasattr(self, '_last_log_time'):
                    self._last_log_time = 0
                
                if current_time - self._last_log_time >= 1.0:
                    print(f"[HotkeyManager] 仍按下: {pressed_keys}")
                    self._last_log_time = current_time
                return
            
            # 所有按键都已释放
            if all_released:
                # 检查是否满足最短按压时间
                press_duration = time.time() - self.last_press_time
                if press_duration < self.min_press_duration:
                    print(f"[HotkeyManager] 按压时间太短 ({press_duration:.3f}s)，忽略")
                    return
                
                print("[HotkeyManager] ========== 所有按键已释放！ ==========")
                self.is_pressed = False
                self.release_timer.stop()
                print("[HotkeyManager] 停止定时器")
                print("[HotkeyManager] >>> 发送 hotkey_released 信号 <<<")
                self.hotkey_released.emit()
                print("[HotkeyManager] hotkey_released 信号已发送！")
        except Exception as e:
            print(f"[HotkeyManager] 检查释放失败: {e}")
            import traceback
            traceback.print_exc()
    
    def cleanup(self):
        """清理资源"""
        self.release_timer.stop()
        self.unregister_hotkey()
        try:
            keyboard.unhook_all()
        except:
            pass

